<?php

namespace App\Common;

use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;

class File {

    //put your code here
    public $path;
    public $filePoint;
    public static $unique = null;
    public static $jpgQuality = 100;
//    public static $userItemImgFolder= '/root/datas/darling/images';
    public static $tempFolder = '';

    public function __construct() {
        
    }

    public static function getTempFolder() {
        return storage_path('app/public/temp');
    }


    public function open($path) {
        $this->path = $path;
        $myfile = fopen($path, "r") or die("Unable to open file!");
        $this->filePoint = $myfile;
    }

    public function toZip($folderPath) {
        $zip = new ZipArchive();
        if ($zip->open('images.zip', ZipArchive::OVERWRITE) === TRUE) {
            addFileToZip('$folderPath/', $zip); //调用方法，对要打包的根目录进行操作，并将ZipArchive的对象传递给方法
            $zip->close(); //关闭处理的zip文件
        }
    }

    public function addFileToZip($path, $zip) {
        $handler = opendir($path); //打开当前文件夹由$path指定。
        while (($filename = readdir($handler)) !== false) {
            if ($filename != "." && $filename != "..") {//文件夹文件名字为'.'和‘..’，不要对他们进行操作
                if (is_dir($path . "/" . $filename)) {// 如果读取的某个对象是文件夹，则递归
                    addFileToZip($path . "/" . $filename, $zip);
                } else { //将文件加入zip对象
                    $zip->addFile($path . "/" . $filename);
                }
            }
        }
        closedir($path);
    }

    // 如果该目录不存在，自动创建该目录
    public static function directory($dir) {
        return is_dir($dir) or ( self::directory(dirname($dir)) and mkdir($dir, 0777));
    }

    public static function createDateFoler($folder) {
        $dateFolderName = date('ynjH');
        $fullFolder = $folder . '/' . $dateFolderName;
        if (!file_exists($fullFolder)) {
            self::directory($fullFolder);
        }
        return $dateFolderName;
    }

    //  返回回完整路径
    public static function createUnique($folder, $fileExtName = null) {
        $subDir = self::createDateFoler($folder);
        $fileUnique = self::fileUnique();
        $extention = '';
        if (!is_null($fileExtName)) {
            $extention = '.' . $fileExtName;
        }
        $subFile = $subDir . '/' . $fileUnique . $extention;
        self::$unique = $subFile;
        return $subFile;  // 
    }

    public static function fileUnique() {
        $fileUnique = uniqid(md5(microtime(true)));
        return $fileUnique;
    }

    public static function shortNameUnique($id) {
        $fileUnique = self::base10to62($id);
        return $fileUnique;
    }

    public static function createUniqueFile($folder, $fileExtName = null) {
        $subFile = self::createUnique($folder, $fileExtName);
        $realFile = $folder . '/' . $subFile;
        return $realFile;
    }

    public static function getUnique($folder = null, $fileExtName = null) {
        if (is_null(self::$unique) && $folder !== null) {
            return self::createUnique($folder, $fileExtName);
        }
        return self::$unique;
    }

    public static function resize2jpeg($srcImg, $desImg, $height = 800) {
        $img = Image::make($srcImg);
        $img->resize(null, $height, function ($constraint) {
            $constraint->aspectRatio();
        });
        $img->save($desImg, self::$jpgQuality);
    }

    public static function resize2uniquejpeg($srcImg, $desFolder, $height = 800) {
        $desImg = self::createUniqueFile($desFolder, 'jpg');
        self::resize2jpeg($srcImg, $desImg, $height);
        return $desImg;
    }

    // 注意使用STORAGE的方法使用的是config/filesystem里面设置的目录，且不支持中文。
    public static function getFileList($directory) {
        $files = Storage::files($directory);
        return $files;
    }

    // 获取某一行内容
    public function getLine() {
        return fgets($this->filePoint);
    }

    public function eof() {
        return feof($this->filePoint);
    }

    public function close() {
        fclose($this->filePoint);
    }

    //   以文件/abc/test.txt为例  
    // 返回test.txt
    public function getFullName() {
        return pathinfo($this->path, PATHINFO_BASENAME);
    }

    // 返回test
    public function getFileName() {
        return pathinfo($this->path, PATHINFO_FILENAME);
    }

    // 返回txt
    public function getExtName() {
        return pathinfo($this->path, PATHINFO_EXTENSION);
    }

    // 返回/abc/test.txt 
    public static function getFullFileName() {
        return pathinfo($this->path, PATHINFO_DIRNAME) . '/' . pathinfo($this->path, PATHINFO_BASENAME);
    }

    // 返回 /abc
    public function getDirName() {
        return pathinfo($this->path, PATHINFO_DIRNAME);
    }

    public function guid() {  // 全局唯一ID
        if (function_exists('com_create_guid')) {
            return com_create_guid();
        } else {
            mt_srand((double) microtime() * 10000); //optional for php 4.2.0 and up.
            $charid = strtoupper(md5(uniqid(rand(), true)));
            $hyphen = chr(45); // "-"
            $uuid = chr(123)// "{"
                    . substr($charid, 0, 8) . $hyphen
                    . substr($charid, 8, 4) . $hyphen
                    . substr($charid, 12, 4) . $hyphen
                    . substr($charid, 16, 4) . $hyphen
                    . substr($charid, 20, 12)
                    . chr(125); // "}"
            return $uuid;
        }
    }

    // modified by lee
    public static  function delete($path = null) {
        if (!is_null($path) &&file_exists($path) ) {
            unlink($path);
        } else {
//             $this->close();
//             unlink($this->path);
        }
    }

    public function get($url) {
        $ch = curl_init();
        // 设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //执行并获取HTML文档内容
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
        return $output;
    }

    public function post($url, $datasArr) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // post数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $datasArr);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    public static function base10to62($num) {
        $to = 'abcBCD567defgh34xyzA89qrstuvwEFGHiMNOPQRSTnop01UVjklm2IJKLWXYZ';
        $toBase = str_split($to);
        $toLen = strlen($to);
        if ($num < strlen($to)) {
            return $toBase[$num];
        }
        $retval = '';
        while ($num != '0') {
            $retval = $toBase[bcmod($num, $toLen)] . $retval;
            $num = bcdiv($num, $toLen, 0);
        }
        return $retval;
    }

    public static function imgRotate($imgPath, $angle) {
        $img = Image::make($imgPath);
        $img->rotate($angle);
        if ($img->height() > 800) {
            $img->resize(null, 800, function ($constraint) {
                $constraint->aspectRatio();
            });
        }
        $img->save($imgPath, self::$jpgQuality);
    }
    
    /**
     * 获取image的存储根路径
     */
    public static function getImgsFolder() {
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
            return env('WIN_IMG_PATH');
        } else {
            return env('IMG_PATH');
        }
    }
    
    /**
     * 获取icon的存储 文件夹名称
     */
    public static  function getIconFolder(){
        return env('ICON_FOLDER');
    }
    /**
     * 获取thumb Icon的存储 文件夹名称
     */
    public static function getThumbIconFolder(){
        return env('ICON_THUMB_FOLDER');
    }
    
    /**
     * 产生时间戳  
     * 返回秒数 与毫秒数 1000000倍的和
     */
    static public function getMicSec(){
        list($micS,$sec)=explode(' ', microtime());
        return (int)($sec+$micS*1000000);
    }
    
    /**
     * 根据 时间戳 的整型数据 转换为  62进制字符
     */
    static public function getImgName(){
        return self::base10to62(self::getMicSec());
    }


    /**
     * 文件上传到服务器，返回文件存储的地址
     * 存储 image对象 和 thumb image 对象
     * @param FileObject $fileObj,文件对象，由request的file方法返回
     * @param string $imgRoot， 文件根目录
     * @param string $imgFolder，存储image的文件夹
     * @param string $thumbImgFolder ，存储thumb image的文件夹
     * @param string $imgName，上传保存图片的名称
     * @param fload $scale ,图片的缩放比例 小于1
     * @param int &$imgWidth , 返回图片的宽度
     * @param int &$imgHeight, 返回图片的高度
     */
    public static function uploadImgFile($fileObj ,$imgRoot ,$imgFolder,
                $thumbImgFolder,$imgName,$scale,&$imgWidth,&$imgHeigh) { 
        if ( $fileObj!=null && $fileObj->isValid()) {
            $fileName = $imgName . '.' . $fileObj->getClientOriginalExtension();
            $imgRootPath= $imgRoot;
            // image 存储路径
            $iconImgPath =$imgRootPath. '/'.$imgFolder;
            // thumb image 存储路径
            $thumbImgPath=$imgRootPath. '/'.$thumbImgFolder;        
            
            $dateFolder = self::createDateFoler($iconImgPath);
            
            $fileFullPath=$iconImgPath . '/' . $dateFolder."/".$fileName;
            // 删除 重复命名文件
//             if(Storage::exists($fileFullPath)){
//                 Storage::delete($fileFullPath);
//             }
            $saveState=$fileObj->move($iconImgPath . '/' . $dateFolder , $fileName);
            // 保持Image成功 保存Thumb Image
            if ($saveState){
                 $dateFolder = self::createDateFoler($thumbImgPath);

                 $thumbImgObj= Image::make($iconImgPath . '/' . $dateFolder.'/'.$fileName);
                 $width=$thumbImgObj->width();
                 $height=$thumbImgObj->height();
                 $imgWidth=$width;
                 $imgHeigh=$height;
                 // 缩略图 比例
                 $thumbImgObj->resize((int)($width*$scale),(int)($height*$scale));
                 $thumbImgObj->save($thumbImgPath.'/'.$dateFolder.'/'.$fileName);
                 // 返回的是user 路径
                 return $imgFolder . '/' . $dateFolder. '/' . $fileName; 
            }else{
                return null;
            }
        } else {
             return null;
        }
    } 
    
    /**
     * 批量删除image 及其 thumb image 
     * @param string $imgRootPath，image的根本路径
     * @param array $imgPathArr,icon的所有 存储路径
     */
    public static function deltImgs($imgRootPath,array $imgPathArr){
        foreach ($imgPathArr as $fileP){
            // 删除已经 上传的icon文件
            self::delete($imgRootPath.'/'.$fileP);
            // 删除已经上传的 thumbicon文件
            $iconFolder=self::getIconFolder();
            $thumbIconFolder=self::getThumbIconFolder();
            $thumbIconPath=str_replace($iconFolder, $thumbIconFolder, $fileP);
            self::delete($imgRootPath.'/'.$thumbIconPath);
        
        }
    }
    
}